//批次号
let lotNo = "";
(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'initStock/add/getProductInfo',
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    if(lotNo.length == 0){
                        //批次号：YPZY+当前日期+三位自动编码
                        lotNo = "YPZY" + getNowFormatDate(2);
                    }
                    let tableData = table.cache["productinformationtableid"];
                    $.each(tableData, function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            data.lotNo = lotNo;
                            tableData[index] = data;
                        }
                    });
                    table.reload('productinformationtableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["productinformationtableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
        }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"),ids="";
layui.use(['tableEdit',"selectInput"], function () {
    let layer = layui.layer,
        selectInput = layui.selectInput;


    //仓库信息
    let warehouseList = [];
    //货位
    let articleNoList = [];
    //客户信息
    let customerInfo = [];
    //供应商
    let materialSupplierList = [];

    layer.ready(function () {

        //货位
        articleNoList = getdictionary(6, 38);

        $("#operator").val(user.name);

        $.ajax({
            url: "purchase/getFilterCustomer2List",
            success: function (res) {
                if (res.status == 200) {
                    materialSupplierList = res.data;
                    materialSupplierList.push({name: "无", code:"无"})
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

        //获取资源仓库信息
        $.ajax({
            url:"resourceSamples/getResourceWarehouseInfo",
            success:function(data){
                if(data.status == 200){
                    warehouseList = data.data;
                    for(let i in data.data){
                        $("#warehouseId").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                    }
                    form.render('select');
                }
            }
        });

        //登记编号：DJ+当前日期+三位自动编码
        let billNo = "DJ" + getNowFormatDate(2);
        $("#billNo").val(billNo);
    })

    /*//客户名称
    let ins = selectInput.render({
        elem: '#customerSelect',
        name: 'customerSelect',
        hasSelectIcon: true,
        placeholder: '请输入名称',
        data: [],
    })
    //监听输入
    ins.on('itemInput(customerSelect)', function (obj) {
        let tempData = [];
        //获取客户信息
        getCustomerInfo(obj.value);
        if(customerInfo){
            for (let i in customerInfo) {
                customerInfo[i]["value"] = customerInfo[i].code;
                tempData.push(customerInfo[i]);
            }
        }else {
            let tmp = {
                name: "未找到",
                value:""
            }
            tempData.push(tmp);
        }
        ins.addSelect(tempData);
    })*/

    /**
     * 获取客户信息
     * @param name 客户名称
     */
    function getCustomerInfo(name) {
        $.ajax({
            url: "basicInformation/getCustomerOfSelf?info=" + name,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                }else {
                    customerInfo = [];
                }
            }
        })
        return;
    }

    // 监听select 选择事件
    /*ins.on('itemSelect(customerSelect)', function (obj) {
        let code = obj.data;
        let name = obj.textContent;
        $("#customerCode").val(code);
        $("#customerName").val(name);
    });*/

    //监听仓库下拉框
    form.on('select(warehouseId)', function (data) {
        if(data.value === ""){
            $("#warehouseName").val("");
            return;
        }
        let name = getWarehouseName(data.value);
        $("#warehouseName").val(name);
        let oldTransferData =  table.cache["productinformationtableid"];
        if(oldTransferData.length > 0){
            for(let i in oldTransferData){
                oldTransferData[i]["warehouseName"] = name;
                oldTransferData[i]["warehouseId"] = data.value;
            }
            table.reload('productinformationtableid',{data : oldTransferData});
        }else {
            return;
        }
    })


    function getWarehouseName(code){
        for(let i in warehouseList){
            if(warehouseList[i].code == code){
                return warehouseList[i].name;
            }
        }
        return "";
    }


    //表单初始值
    if (id != "") {
        ids = id.split(",");//id为多个数组存储
        form.val("editor-form", {
            "receiptnumber": "单据编号",
        })
    }

    //监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取表单信息数据
        let detail = table.cache["productinformationtableid"];
        if(detail.length > 0){
            for(let i in detail){
                let num = parseInt(i) + 1;
                //字段校验
                if(!checkData(detail[i], num)){
                    return false;
                }
            }
        }

        req["details"] = detail;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"resourceSamples/add/register",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/samplesresources.jsp");
                        parent.intab("views/jsp/WarehouseManagement/samplesresources.jsp", "工厂仓库");
                        parent.detab("views/jsp/WarehouseManagement/tpl/registration.jsp" + (id == '' ? '' : '?id=' + id));
                    }, );
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    });

    function checkData(data, i) {
        if(isEmpty(data.warehouseName)){
            layer.msg("第"+ i +"行：仓库名称不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productNum)){
            layer.msg("第"+ i +"行：数量不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productUnit)){
            layer.msg("第"+ i +"行：单位不能为空，请产品维护", {icon: 5});
            return false;
        }
        if(isEmpty(data.articleNo)){
            layer.msg("第"+ i +"行：货位不能为空", {icon: 5});
            return false;
        }
        return true;
    }
    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

//--入库产品信息
    let initData = [];
    table.render({
        elem: '#productinformation',
        id: 'productinformationtableid',
        data: initData,
        toolbar: '#productinformationtoolbar',
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'img', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'productCode', width: 220, title: '产品编码', templet: '#productcodeselect'},
            {field: 'specificationCode', width: 120, title: '规格编码', edit: 'text'},
            {field: 'productCname', width: 120, title: '中文名称', edit: 'text'},
            {field: 'productEname', width: 120, title: '英文名称', edit: 'text'},
            {field: 'productCdesc', width: 120, title: '中文描述', edit: 'text'},
            {field: 'productEdesc', width: 120, title: '英文描述', edit: 'text'},
            {field: 'unitPrice', width: 120, title: '单价', edit: 'text'},
            {field: 'productNum', width: 120, title: '数量', edit: 'text'},
            {field: 'productUnit', width: 120, title: '单位'},
            {field: 'articleNo', width: 220, title: '货位', templet: '#articleNoSelect'},
            {field: 'supplierCode', title: '供应商', width: 240, templet: '#materialSupplierSelect'},
            {field: 'lotNo', width: 180, title: '批次号'},
            {field: 'warehouseId', width: 160, title: '资源样品仓库', templet: '#resourcesamplewarehouse'},
            {field: 'specificationExplanation', width: 120, title: '备注', edit: 'text'},
        ]],
        page: true,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            //显示大图
            hoverOpenImg();
            for(let i in warehouseList){
                $(".warehouse").append("<option value=\"" + warehouseList[i].code + "\">" + warehouseList[i].name + "</option>");
            }
            for(let i in articleNoList){
                $(".articleNo").append("<option value=\"" + articleNoList[i].name + "\">" + articleNoList[i].name + "</option>");
            }
            //供应商
            for(let i in materialSupplierList){
                $(".supplierCode").append("<option value=\"" + materialSupplierList[i].code + "\">" + materialSupplierList[i].name + "</option>");
            }
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                let classs = ".y_" + tempId;
                $(classs).ySearchSelect(classs);
                $("#warehouse_" + tempId).val(res.data[i].warehouseId);
                $("#articleNo_" + tempId).val(res.data[i].articleNo);
                $("#supplierCode_" + tempId).val(res.data[i].supplierCode);
            }
            form.render('select');
        }
    });

    //监听供应商下拉框
    form.on("select(materialSupplierSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataindex = elem.attr("data-index");
        let tabledata = table.cache["productinformationtableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["supplierCode"] = data.value;
                tabledata[index]["supplierName"] = getMaterialSupplierName(data.value);
            }
        });
    });
    function getMaterialSupplierName(code){
        for(let i in materialSupplierList){
            if(materialSupplierList[i].code == code){
                return materialSupplierList[i].name;
            }
        }
        return "";
    }

    form.on("select(articleNoSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["productinformationtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["articleNo"] = data.value;
            }
        });
    });

    form.on("select(resourcesamplewarehouse_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["productinformationtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["warehouseId"] = data.value;
                tableData[index]["warehouseName"] = getWarehouseName(data.value);
            }
        });
    });

    function getWarehouseName(code){
        for(let i in warehouseList){
            if(warehouseList[i].code == code){
                return warehouseList[i].name;
            }
        }
        return "";
    }

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    table.on('edit(productinformationtable)', function (obj) {
        var old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "unitPrice" || obj.field == "productNum") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
    });

    function isNumber(val) {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    function tobottomfn(id){
        let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
        let h=d.scrollHeight
        d.scrollTo(0,h)
    }

    table.on('toolbar(productinformationtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'productlibraryimport':
                if(lotNo.length == 0){
                    //批次号：YPZY+当前日期+三位自动编码
                    lotNo = "YPZY" + getNowFormatDate(2);
                }
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/WarehouseManagement/tpl/productlibraryimport.jsp?lotNo='+lotNo
                });
                break;
            case 'purchaseImport':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/WarehouseManagement/tpl/purchaseImport.jsp'
                });
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', confirmInfo(3,5), function (index) {
                        let cbList = table.cache["productinformationtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("productinformationtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
            case 'new':
                let oldData = table.cache["productinformationtableid"];
                if(lotNo.length == 0){
                    //批次号：YPZY+当前日期+三位自动编码
                    lotNo = "YPZY" + getNowFormatDate(2);
                }
                let data1 = {
                    "tempId": oldData.length + 1,
                    "img": "",
                    "productCode": "",
                    "specificationCode": "",
                    "specificationExplanation": "",
                    "productCname": "",
                    "productEname": "",
                    "productCdesc": "",
                    "productEdesc": "",
                    "unitPrice": "",
                    "productNum": "",
                    "productUnit": "",
                    "articleNo": "",
                    "lotNo": lotNo,
                    "warehouseId": "",
                    "supplierCode":"无"
                };
                oldData.push(data1);
                table.reload('productinformationtableid', {data: oldData});
                tobottomfn("productinformationtableid");
                break;
        }
        ;
    });
});

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}

let currentDate = getNowFormatDate(1);
//创建时间
layui.laydate.render({
    elem: '#createDate',
    value: currentDate,
    min: currentDate,
    max: currentDate,
    btns: ['confirm']
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}